<template>
  <div class="employee-edit-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <t-button theme="default" variant="text" @click="handleBack" class="back-btn">
            <template #icon>
              <t-icon name="chevron-left" />
            </template>
            返回列表
          </t-button>
          <div class="page-title">
            <t-icon name="user" class="title-icon" />
            <span>编辑员工信息</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <t-row :gutter="[24, 24]">
        <!-- 左侧信息卡片 -->
        <t-col :span="6">
          <t-card title="基本信息" :bordered="false" class="info-card" :header-bordered="false">
            <template #header>
              <div class="card-header">
                <t-icon name="user-circle" class="card-icon" />
                <span>基本信息</span>
              </div>
            </template>

            <!-- 头像上传区域 -->
            <div
              class="avatar-upload"
              @mouseenter="showPlus = true"
              @mouseleave="showPlus = false"
              style="position: relative"
            >
              <!-- 头像图片 -->
              <t-avatar :image="formData.avatarUrl" size="180px" class="avatar-img" />
              <!-- 鼠标悬浮时显示的+号按钮，绝对定位在头像中央 -->
              <div v-show="showPlus" class="avatar-plus-btn" @click="triggerUpload">
                <span class="plus-icon">+</span>
              </div>
              <!-- 隐藏的input[type=file]，用于手动触发文件选择 -->
              <input ref="fileInputRef" type="file" accept="image/*" style="display: none" @change="onFileChange" />
            </div>

            <!-- 基本信息表单 -->
            <t-form :data="formData" :rules="formRules" ref="formRef" :label-width="80" class="basic-form">
              <t-form-item label="用户名" name="username">
                <t-input
                  v-model="formData.username"
                  placeholder="请输入用户名"
                  clearable
                  :maxlength="20"
                  show-limit-number
                  class="username-input"
                />
              </t-form-item>
            </t-form>

            <!-- 操作按钮区域 -->
            <div class="action-buttons">
              <t-space>
                <t-button theme="primary" @click="handleSave">
                  <template #icon>
                    <t-icon name="check" />
                  </template>
                  保存更改
                </t-button>
                <t-button theme="default" variant="outline" @click="handleReset">
                  <template #icon>
                    <t-icon name="refresh" />
                  </template>
                  重置
                </t-button>
              </t-space>
            </div>
          </t-card>
        </t-col>
      </t-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getEmployeeDetail, updateEmployee } from '@/api/employee';
import type { EmployeeUpdateRequest } from '@/api/model/employeeModel';
import { checkFileSize, commonFileUpload } from '@/utils/upload';
import { MessagePlugin } from 'tdesign-vue-next';
import { onActivated, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
// 定义组件名称
defineOptions({ name: 'EmployeeEdit' });

// 路由相关
const router = useRouter();
const route = useRoute();

// 表单数据
const formData = ref<EmployeeUpdateRequest>({
  id: 0,
  username: '',
  avatarUrl: '',
  status: 0,
  role: '',
});

// 表单校验规则
const formRules = {
  username: [
    { required: true, message: '用户名不能为空', type: 'error' as const },
    {
      validator: (val: string) => {
        const valid = /^[\u4e00-\u9fa5]+$/.test(val);
        return valid ? true : { result: false, message: '用户名必须为中文', type: 'error' as const };
      },
      message: '用户名必须为中文',
      type: 'error' as const,
    },
  ],
};

// 响应式数据
const formRef = ref();

// 控制+号显示的变量
const showPlus = ref(false); // 是否显示+号
const fileInputRef = ref(); // input[type=file]的ref

// 触发上传文件选择框的方法
const triggerUpload = () => {
  // 通过ref手动触发input[type=file]的点击
  fileInputRef.value && fileInputRef.value.click();
};

// 监听input[type=file]的change事件，选中文件后手动上传
const onFileChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (files && files.length > 0) {
    const file = files[0];

    // 检查文件大小
    if (!checkFileSize(file, 5, true)) {
      // 清空input值
      (e.target as HTMLInputElement).value = '';
      return;
    }

    const result = await commonFileUpload(file, false, (url: string) => {
      formData.value.avatarUrl = url;
      MessagePlugin.success('头像上传成功');
    });

    // 处理上传失败的情况
    if (result.status === 'fail') {
      MessagePlugin.error('网络异常，头像上传失败');
    }

    // 清空input值，避免同一文件无法重复上传
    (e.target as HTMLInputElement).value = '';
  }
};

/**
 * 页面初始化
 */
onActivated(async () => {
  const employeeId = route.params.id;
  if (employeeId) {
    await loadEmployeeData(Number(employeeId));
  }
});

/**
 * 加载员工数据
 */
const loadEmployeeData = async (id: number) => {
  try {
    // 调用获取员工详情的API
    const res = await getEmployeeDetail(id);
    const data = res.data.data;
    formData.value = {
      id: data.id,
      username: data.username,
      avatarUrl: data.avatarUrl,
      status: data.status,
      // 最后一个权限角色
      role: data.role[data.role.length - 1] || ['PATIENT'],
    };
  } catch (error: any) {
    MessagePlugin.error(error.message || '加载员工数据失败');
  }
};

/**
 * 返回列表页面
 */
const handleBack = () => {
  router.push('/employee');
};

/**
 * 重置表单
 */
const handleReset = async () => {
  try {
    const employeeId = route.params.id;
    if (employeeId) {
      await loadEmployeeData(Number(employeeId));
    }
    MessagePlugin.success('重置成功');
  } catch (error) {
    MessagePlugin.error('重置失败');
  }
};

/**
 * 保存更改
 */
const handleSave = async () => {
  // 先校验表单
  const valid = await formRef.value.validate();
  if (valid !== true) {
    return;
  }

  try {
    await updateEmployee(formData.value);
    MessagePlugin.success('保存成功');
  } catch (error: any) {
    MessagePlugin.error(error.message || '保存失败');
  }
};
</script>

<style lang="less" scoped>
.employee-edit-container {
  min-height: 100vh;
  background-color: var(--td-bg-color-page);
  padding: 0;

  // 页面头部样式
  .page-header {
    background: linear-gradient(135deg, var(--td-brand-color-1) 0%, var(--td-brand-color-2) 100%);
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);
    border-bottom: 1px solid var(--td-border-level-1-color);
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 2px;
      background: linear-gradient(90deg, var(--td-brand-color) 0%, var(--td-brand-color-1) 100%);
    }

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      max-width: 1200px;
      margin: 0 auto;

      .header-left {
        display: flex;
        align-items: center;
        gap: 24px;

        .back-btn {
          color: var(--td-text-color-primary);
          font-weight: 500;

          &:hover {
            background-color: var(--td-bg-color-container-hover);
          }
        }

        .page-title {
          display: flex;
          align-items: center;
          gap: 12px;
          font-size: 24px;
          font-weight: 600;
          color: var(--td-text-color-primary);

          .title-icon {
            font-size: 28px;
            color: var(--td-brand-color);
          }
        }
      }

      .header-right {
        .t-button {
          border-radius: var(--td-radius-medium);
          font-weight: 500;
          min-width: 100px;
        }
      }
    }
  }

  // 主要内容区域
  .main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);

    // 卡片通用样式
    .t-card {
      border-radius: var(--td-radius-large);
      box-shadow: var(--td-shadow-1);
      border: 1px solid var(--td-border-level-1-color);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: var(--td-shadow-2);
        transform: translateY(-2px);
      }

      .card-header {
        display: flex;
        align-items: center;
        gap: 12px;
        font-weight: 600;
        color: var(--td-text-color-primary);

        .card-icon {
          font-size: 20px;
          color: var(--td-brand-color);
        }
      }
    }

    // 信息卡片样式
    .info-card {
      .avatar-section {
        margin-bottom: 32px;

        .avatar-container {
          position: relative;
          display: inline-block;
          margin-bottom: 16px;

          .user-avatar {
            border: 4px solid var(--td-border-level-1-color);
            transition: all 0.3s ease;
            cursor: pointer;

            &:hover {
              border-color: var(--td-brand-color);
              transform: scale(1.05);
            }
          }

          .avatar-overlay {
            position: absolute;
            bottom: 8px;
            right: 8px;
            opacity: 0;
            transition: all 0.3s ease;

            .upload-btn {
              border-radius: var(--td-radius-medium);
              font-weight: 500;
            }
          }

          &:hover .avatar-overlay {
            opacity: 1;
          }
        }

        .avatar-tips {
          display: flex;
          align-items: center;
          gap: 8px;
          color: var(--td-text-color-placeholder);
          font-size: 13px;

          .tips-icon {
            font-size: 14px;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .employee-edit-container {
    .page-header {
      padding: var(--td-comp-paddingTB-lg) var(--td-comp-paddingLR-lg);

      .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;

        .header-left {
          flex-direction: column;
          gap: 12px;
        }
      }
    }

    .main-content {
      padding: var(--td-comp-paddingTB-lg) var(--td-comp-paddingLR-lg);
    }
  }
}

// 深色模式优化
:root[theme-mode='dark'] {
  .employee-edit-container {
    .page-header {
      background: linear-gradient(135deg, var(--td-brand-color-2) 0%, var(--td-brand-color-3) 100%);
    }

    .main-content {
      .t-card {
        box-shadow: var(--td-shadow-2);

        &:hover {
          box-shadow: var(--td-shadow-3);
        }
      }
    }
  }
}

.avatar-upload {
  position: relative; // 使+号绝对定位于头像区域
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}
.avatar-img {
  margin-bottom: 16px;
  border: 2px solid #f0f0f0;
  // 让头像容器成为定位参考
  position: relative;
}
.avatar-upload-btn {
  margin-top: 0;
}
.avatar-plus-btn {
  // 绝对定位在头像正中央
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 80px; // 加号按钮更大
  height: 80px;
  background: rgba(0, 0, 0, 0.5); // 半透明黑色背景
  color: #fff;
  font-size: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 2;
  transition: opacity 0.2s;
  opacity: 0.9;
  user-select: none;
  // 只在头像区域上方
  pointer-events: auto;
}

// 操作按钮区域样式
.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;

  .t-button {
    min-width: 120px;
    border-radius: var(--td-radius-medium);
    font-weight: 500;
  }
}
</style>
